package com.designpattern.softwaredesignpatternstudy.pattern.prototype;

import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.lang.reflect.Constructor;

/**
 * @Author: Jiangxx
 * @Date: 2021/09/30
 * @Description: 创建对象的方式
 */
public class CreateObjectWays {
    public static void main(String[] args) throws Exception {
        // 方式1 new
        ObjectTest objectTest = new ObjectTest();
        System.out.println(objectTest);
        // 方式二 反射
        ObjectTest o = (ObjectTest) Class.forName("com.designpattern.softwaredesignpatternstudy.pattern.prototype.ObjectTest").newInstance();
        System.out.println(o);

        Constructor<ObjectTest> constructor = ObjectTest.class.getConstructor();
        ObjectTest objectTest1 = constructor.newInstance();
        System.out.println(objectTest1);

        // 方式三 clone
        ObjectTest clone = (ObjectTest) objectTest.clone();
        System.out.println(clone);

        // 方式四 反序列化
        ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("data.obj"));
        ObjectTest o1 = (ObjectTest) objectInputStream.readObject();
        System.out.println(o1);
    }
}

class ObjectTest implements Cloneable, Serializable {

    @Override
    public Object clone() throws CloneNotSupportedException {
        return (ObjectTest) super.clone();
    }

}